package com.shun.gen.service;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.PrintWriter;
import java.util.Properties;

/**
 * 配置MyBatis的数据源
 * @author clever
 * @since  2021-10-11
 */
public class GenCodeConfig {

    //URL
    private static final String URL = "jdbc:mysql://172.21.11.15:3306/shundb?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";

    //连接数据库的用户名
    private static final String USRENAME = "root";

    //连接数据库的密码
    private static final String PASSWORD = "root";


    /**
     * 配置数据源
     * @return
     */
    public HikariDataSource getDS(){
        Properties props = new Properties();
        props.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver");
        props.setProperty("jdbcUrl", URL);
        props.setProperty("dataSource.user", USRENAME);
        props.setProperty("dataSource.password", PASSWORD);
        props.setProperty("dataSource.databaseName", "shundb");
        props.put("dataSource.logWriter", new PrintWriter(System.out));
        HikariConfig config = new HikariConfig(props);
        HikariDataSource ds = new HikariDataSource(config);
        return ds;
    }

    /**
     * 获取会话工厂
     * @return
     */
    public SqlSessionFactory getFactory(){
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development",transactionFactory,getDS());
        Configuration configuration = new Configuration(environment);
        configuration.addMappers("com.shun.gen.mapper");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        return sqlSessionFactory;
    }

    public static void main(String[] args) {

        new GenCodeConfig().getDS();


    }

}
